<template>
  <div class="login-container">
    <!-- $router.back() 一定要加括号 -->
    <van-nav-bar
      class="app-nav-bar"
      title="注册 / 登录"
      left-arrow
      @click-left="$router.back()"
    />
    <van-form
      :show-error="false"
      :show-error-message="false"
      validate-first
      @submit="onLogin"
      @failed="onFailed"
    >
    <van-field
      v-model="userForm.username"
      left-icon="manager-o"
      center
      placeholder="请填写用户名！"
      :rules="[
        { required: true, message: '请填写用户名！' }
      ]"
      name="username"
    />
    <!--
      vue input 警告[DOM] Input elements should have autocomplete attributes (suggested: "current-pass
      autocomplete 用途: 此功能主要是记住输入内容，下次提交表单或者浏览器回退后，还能保持表单内容不变。
    -->
    <van-field
      v-model="userForm.password"
      left-icon="edit"
      center
      type="password"
      placeholder="请输入密码"
      autocomplete
    />
    <div class="login-btn-wrap">
      <!-- <span class="tips">注意：首次登录自动注册</span> -->
      <van-button
        class="login-btn"
        type="info"
        block
      >登录</van-button>
    </div>
    </van-form>
  </div>
</template>

<script>
import { login } from '@/api/user'
export default {
  name: 'LoginIndex',
  components: {},
  props: {},
  data () {
    return {
      userForm: {
        username: 'admin',
        password: 'admin'
      }
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    onLogin () {
      // console.log('表单验证通过')
      this.$toast.loading({
        message: '登录中...', // 提示文本
        forbidClick: true, // 禁止背景点击
        duration: 0 // 展示时长ms 值为0时 toast不会消失
      })
      // this.$toast.success('登录成功')
      // this.$router.push('/')
      // console.log('this.userForm', this.userForm)
      login(this.userForm).then(res => {
        // console.log('login res', res)
        if (res.data.errno === 1000) {
          this.$toast.success('登录成功')
          this.$store.commit('SET_USER', res.data.data)
          this.$router.push('/')
        }
      }).catch(err => {
        console.log('login err', err)
        this.$toast.fail('登录失败')
      })
    },
    onFailed (errorInfo) {
      // console.log('表单验证不通过')
      console.log('failed', errorInfo)
      this.$toast.fail(`${errorInfo.errors[0].message}`)
    }
  }
}
</script>

<style scoped lang="scss">
// .login-btn-wrap {
//   padding: 0px 16px;
//   .login-btn {
//     background-color: #6db4fb;
//     border: none;
//     .van-button__text {
//       font-size: 15px;
//     }
//   }
// }
.tips {
  font-size: 12px;
  color: #888;
}
</style>
